<template>
  <label class="v-radio"
    :class="{
      'is-disabled': isDisabled,
      'is-checked': model === label,
      'is-focus': focus
    }"
  >
    <span class="v-radio__input">
      <span class="v-radio__inner"></span>
      <input
        class="v-radio__original"
        :value="label"
        type="radio"
        v-model="model"
        @focus="focus = true"
        @blur="focus = false"
        :name="name"
        :disabled="isDisabled">
    </span>
    <span class="v-radio__label">
      <slot></slot>
      <template v-if="!$slots.default">{{label}}</template>
    </span>
  </label>
</template>
<script>
  import Emitter from '@/vuego/mixins/emitter';

  export default {
    name: 'VRadio',
    componentName: 'VRadio',
    mixins: [Emitter],
    props: {
      value: {},
      label: {},
      disabled: Boolean,
      name: String,
    },
    data() {
      return {
        focus: false,
      };
    },
    computed: {
      isGroup() {
        let parent = this.$parent;
        while (parent) {
          if (parent.$options.componentName !== 'VRadioGroup') {
            parent = parent.$parent;
          } else {
            this.radioGroup = parent;
            return true;
          }
        }
        return false;
      },
      model: {
        get() {
          return this.isGroup ? this.radioGroup.value : this.value;
        },

        set(val) {
          if (this.isGroup) {
            this.dispatch('VRadioGroup', 'input', [val]);
          } else {
            this.$emit('input', val);
          }
        },
      },
      isDisabled() {
        if (this.isGroup) {
          return this.radioGroup.disabled || this.disabled;
        }
        return this.disabled;
      },
    },
  };
</script>
